#include "user_fatfs.h"
#include "fatfs/ff.h"
SYS_FATFS_OpenFolderInfo User_OpenFolderInfo;
FRESULT __f_res;
FILINFO __f_info;
FATFS __fs;
DIR __f_dir;
FIL __f_file;
char FATFS_Init(void) {
    __f_res = f_mount(&__fs, "0:", 1);
    if (__f_res != FR_OK) {
        return -1;
    }
    return 0;
}
/*
 * @函数：打开文件夹
 */
char FATFS_OpenFolder(const char *Path) {
    User_OpenFolderInfo.Folder_Src=Path;
    User_OpenFolderInfo.File_ListNum=0;
    if (__f_res == FR_OK) {
        __f_res = f_opendir(&__f_dir, Path);
        while (1) {
            __f_res = f_readdir(&__f_dir, &__f_info);
            if (__f_info.fname[0] == 0) break;//无文件退出
            User_OpenFolderInfo.File_List[User_OpenFolderInfo.File_ListNum]= sdsnew(__f_info.fname);
            User_OpenFolderInfo.File_ListNum++;
        }
    }
    return 0;
}
char FATFS_CloseFolder(const char *Path){

}
char FATFS_SaveJpg(uint32_t* buf,const char *Path){
    uint32_t i, jpgstart, jpglen = 0;
    uint8_t* jpgp = (uint8_t *) buf;
    uint8_t headok = 0;
    for (i = 0; i < 5000*4; i++) {
        if ((jpgp[i] == 0XFF) && (jpgp[i + 1] == 0XD8) && (jpgp[i + 2] == 0xFF) && (jpgp[i + 3] == 0xE0)&& (!headok)) {
            jpgstart = i;
            headok = 1;
        }
        if ((jpgp[i] == 0XFF) && (jpgp[i + 1] == 0XD9) && headok) {
            jpglen = i - jpgstart + 2;
            break;
        }
    }
    UINT bw;
    if(jpglen!=0){
        __f_res = f_open(&__f_file, Path,FA_CREATE_ALWAYS|FA_WRITE);
        __f_res= f_write(&__f_file,jpgp,jpglen,&bw);
        __f_res= f_close(&__f_file);
    }

    return 0;
}